package com.zhiche.lisa.lspm.service.otm.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.core.utils.XmlUtil;
import com.zhiche.lisa.lspm.dao.model.carrier.CarrierInfo;
import com.zhiche.lisa.lspm.dao.model.carrier.CarrierTrailerBind;
import com.zhiche.lisa.lspm.dao.model.driver.Driver;
import com.zhiche.lisa.lspm.dao.model.driver.DriverCarrierBind;
import com.zhiche.lisa.lspm.dao.model.driver.DriverCheckin;
import com.zhiche.lisa.lspm.dao.model.driver.DriverLicense;
import com.zhiche.lisa.lspm.dao.model.lsp.LspInfo;
import com.zhiche.lisa.lspm.dao.model.trailer.TrailerInfo;
import com.zhiche.lisa.lspm.service.carrier.ICarrierInfoService;
import com.zhiche.lisa.lspm.service.carrier.ICarrierTrailerBindService;
import com.zhiche.lisa.lspm.service.driver.IDriverLicenseService;
import com.zhiche.lisa.lspm.service.driver.IDriverService;
import com.zhiche.lisa.lspm.service.driver.impl.DriverCarrierBindServiceImpl;
import com.zhiche.lisa.lspm.service.lsp.LspInfoService;
import com.zhiche.lisa.lspm.service.otm.IOtmLisaCarrierService;
import com.zhiche.lisa.lspm.service.otm.ITransToOTMService;
import com.zhiche.lisa.lspm.service.trailer.TrailerInfoService;
import com.zhiche.lisa.lspm.service.utils.MdmUtil;
import com.zhiche.lisa.lspm.vo.common.TransportationTypeVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 和OTM的接口
 */
@Service
public class TransToOTMServiceImpl implements ITransToOTMService {

    @Autowired
    private MdmUtil mdmUtil;

    @Autowired
    private IOtmLisaCarrierService otmLisaCarrierService;

    @Autowired
    private IDriverLicenseService driverLicenseService;

    @Autowired
    private LspInfoService lspInfoService;

    @Autowired
    private ICarrierTrailerBindService carrierTrailerBindService;

    @Autowired
    private ICarrierInfoService carrierInfoService;

    @Autowired
    private TrailerInfoService trailerInfoService;

    @Autowired
    private DriverCarrierBindServiceImpl driverCarrierBindService;

    @Autowired
    private IDriverService driverService;

    @Value("${otm.sendLspUrl}")
    private String sendLspUrl;

    @Value("${otm.sendDriverUrl}")
    private String sendDriverUrl;

    @Value("${otm.sendCarrierUrl}")
    private String sendCarrierUrl;

    @Value("${otm.sendCheckInUrl}")
    private String sendCheckInUrl;

    @Value("${otm.callbackUrl}")
    private String callbackUrl;

    //标识前缀
    private static String prefix = "ULC/ZC.";

    @Override
    public void sendLspToOtm(Long lspId) throws BaseException {
        LspInfo lspInfo = lspInfoService.selectById(lspId);
        //判断承运商列表是否为空
        if (Objects.isNull(lspInfo)) {
            throw new BaseException("承运商为空，不能上传到OTM ");
        }
        String filePath = "classpath:otmxml/servprov.xml";
        Document document = getDocumentByFile(filePath);
        if (Objects.isNull(document)) {
            throw new BaseException("文档不存在或者转化有误");
        }
        String xmlStr = XmlUtil.xmlToString(document);

        //回调地址
        xmlStr = xmlStr.replace("${callbackUrl}",callbackUrl);

        // 承运商编码
        xmlStr = xmlStr.replace("${LocationGid}", lspInfo.getId().toString());
        // 承运商全称
        xmlStr = xmlStr.replace("${LocationName}", lspInfo.getName());
        // 承运商地址
        xmlStr = xmlStr.replace("${Description}", lspInfo.getWorkingSite());
        // 承运商简称
        xmlStr = xmlStr.replace("${Attribute1}", lspInfo.getNameAbbr());

        // 服务类型
        if (!StringUtils.isEmpty(lspInfo.getServiceType())) {
            String serviceType = mdmUtil.getServiceTypeByCodes(lspInfo.getServiceType());
            if (serviceType.contains("板车运输")) {
                serviceType = serviceType.replaceAll("板车运输", "公路");
            }
            if (serviceType.contains("铁路运输")) {
                serviceType = serviceType.replaceAll("铁路运输", "铁运");
            }
            if (serviceType.contains("人送地跑")) {
                serviceType = serviceType.replaceAll("人送地跑", "人送");
            }
            if (serviceType.contains("船运")) {
                serviceType = serviceType.replaceAll("船运", "水运");
            }
            xmlStr = xmlStr.replace("${Attribute4}", serviceType);
        }

        // 法人
        xmlStr = xmlStr.replace("${Attribute7}", lspInfo.getLegalRep());
        // 法人电话
        xmlStr = xmlStr.replace("${Attribute8}", lspInfo.getRepMobile());
        // 状态编码
        if (lspInfo.getStatus() != null &&
                lspInfo.getStatus() == 1) {
            xmlStr = xmlStr.replace("${IsActive}", "Y");
        } else {
            xmlStr = xmlStr.replace("${IsActive}", "N");
        }

        //发送请求到OTM
        String requestResult = HttpClientUtil.post(sendLspUrl, xmlStr);
        if (StringUtils.isEmpty(requestResult)) {
            throw new BaseException("OTM返回值为空");
        }

        try {
            //获取接口请求id
            requestResult = requestResult.replaceAll(" xmlns:ns2=\\\"http://xmlns.oracle.com/apps/gtm/transmission/v6.4\\\" xmlns=\\\"http://xmlns.oracle.com/apps/otm/transmission/v6.4\\\"", "");
            Document document1 = XmlUtil.parseByString(requestResult);
            String nodePath = "/TransmissionAck/EchoedTransmissionHeader/TransmissionHeader/ReferenceTransmissionNo";
            //得到根节点
            Element element = (Element) document1.selectSingleNode(nodePath);
            //得到根节点的值
            String requestId = element.getText();

            //添加
            otmLisaCarrierService.insertOtmLisa(lspInfo.getId(), null, null, null, sendLspUrl, requestId);
        } catch (Exception ex) {
            throw new BaseException(ex.getMessage());
        }
    }

    @Override
    public void sendDriverToOtm(Long driverId) throws BaseException {

        Driver driver = driverService.selectById(driverId);
        //判断司机列表是否为空
        if (Objects.isNull(driver)) {
            throw new BaseException("司机信息为空，不能上传到OTM ");
        }

        String filePath = "classpath:otmxml/driver.xml";
        Document document = getDocumentByFile(filePath);

        if (Objects.isNull(document)) {
            throw new BaseException("文档不存在或者转化有误");
        }

        String xmlStr = XmlUtil.xmlToString(document);

        //回调地址
        xmlStr = xmlStr.replace("${callbackUrl}",callbackUrl);

        // 司机编码
        xmlStr = xmlStr.replace("${DriverGid}", driver.getId().toString());
        // 司机名称
        xmlStr = xmlStr.replace("${FirstName}", driver.getName());

        // 是否生效
        if (driver.getStatus() != null
                && driver.getStatus() == 1) {
            xmlStr = xmlStr.replace("${IsActive}", "Y");
        } else {
            xmlStr = xmlStr.replace("${IsActive}", "N");
        }

        // 司机电话
        xmlStr = xmlStr.replace("${Attribute1}", driver.getMobile());

        //司机证照
        Wrapper<DriverLicense> driverLicenseWrapper = new EntityWrapper<>();
        driverLicenseWrapper.eq("driver_id", driver.getId());
        driverLicenseWrapper.eq("license_type_id", 1);
        List<DriverLicense> driverLicenseList = driverLicenseService.selectList(driverLicenseWrapper);


        // 身份证号
        if (!CollectionUtils.isEmpty(driverLicenseList)) {
            DriverLicense driverLicense = driverLicenseList.get(0);
            xmlStr = xmlStr.replace("${Attribute2}", driverLicense.getLicenseId());
        }
        // 驾驶证类型
        if (driver.getDrivingLicenseType() != null) {
            String drivingLicenseType = driver.getDrivingLicenseType().replaceAll(";", ",");
            xmlStr = xmlStr.replace("${Attribute4}", drivingLicenseType);
        }
        // 分供方编码
        if (driver.getLspId() != null) {
            LspInfo lspInfo = lspInfoService.selectById(driver.getLspId());
            if (lspInfo != null) {
                xmlStr = xmlStr.replace("${Attribute5}", prefix + lspInfo.getId().toString());
            }
        }
        // 服务类型
        if (driver.getServiceType() != null) {
            String serviceType = driver.getServiceType().replaceAll(";", ",");
            xmlStr = xmlStr.replace("${Attribute6}", serviceType);
        }

        String requestResult = HttpClientUtil.post(sendDriverUrl, xmlStr);
        if (StringUtils.isEmpty(requestResult)) {
            throw new BaseException("OTM返回值为空");
        }

        try {
            requestResult = requestResult.replaceAll(" xmlns:ns2=\\\"http://xmlns.oracle.com/apps/gtm/transmission/v6.4\\\" xmlns=\\\"http://xmlns.oracle.com/apps/otm/transmission/v6.4\\\"", "");
            Document document1 = XmlUtil.parseByString(requestResult);
            String nodePath = "/TransmissionAck/EchoedTransmissionHeader/TransmissionHeader/ReferenceTransmissionNo";
            //得到根节点
            Element element = (Element) document1.selectSingleNode(nodePath);
            String requestId = element.getText();
            //添加
            Long lspId = driver.getLspId();
            otmLisaCarrierService.insertOtmLisa(lspId, driver.getId(), null, null, sendDriverUrl, requestId);
        } catch (Exception ex) {
            throw new BaseException(ex.getMessage());
        }
    }

    @Override
    public void sendCarrierToOtm(Long carrierId) throws BaseException {
        CarrierInfo carrierInfo = carrierInfoService.selectById(carrierId);
        //判断牵引车列表是否为空
        if (Objects.isNull(carrierInfo)) {
            throw new BaseException("牵引车信息为空，不能上传到OTM ");
        }
        String filePath = "classpath:otmxml/powerunit.xml";
        Document document = getDocumentByFile(filePath);
        String xmlStr = XmlUtil.xmlToString(document);
        Long lspId = null;
        Long trailerId = null;
        Long driverId = null;

        //回调地址
        xmlStr = xmlStr.replace("${callbackUrl}",callbackUrl);

        // 车牌
        xmlStr = xmlStr.replace("${PowerUnitGid}", carrierInfo.getPlate());
        // 是否生效
        if (Objects.nonNull(carrierInfo.getStatus())
                && carrierInfo.getStatus().equals(1)) {
            xmlStr = xmlStr.replace("IsActive", "Y");
        } else {
            xmlStr = xmlStr.replace("IsActive", "N");
        }
        // 分供方编码
        LspInfo lspInfo = lspInfoService.selectById(carrierInfo.getLspId());
        if (lspInfo != null) {
            lspId = lspInfo.getId();
            xmlStr = xmlStr.replace("${Attribute5}", prefix + lspId.toString());
        }

        // 车辆类型
        Wrapper<CarrierTrailerBind> carrierTrailerBindWrapper = new EntityWrapper<>();
        carrierTrailerBindWrapper.eq("carrier_id", carrierInfo.getId());
        List<CarrierTrailerBind> carrierTrailerBindList = carrierTrailerBindService.selectList(carrierTrailerBindWrapper);
        if (CollectionUtils.isNotEmpty(carrierTrailerBindList)) {
            CarrierTrailerBind carrierTrailerBind = carrierTrailerBindList.get(0);
            trailerId = carrierTrailerBind.getTrailerId();
            //得到挂车信息
            TrailerInfo trailerInfo = trailerInfoService.selectById(trailerId);
            if (Objects.nonNull(trailerInfo)) {
                // 车挂号
                xmlStr = xmlStr.replace("${Attribute2}", trailerInfo.getPlate());
                String trailerType = trailerInfo.getTrailerType();
                if (Objects.nonNull(trailerType)) {
                    TransportationTypeVO transportationType = mdmUtil.getTransportTypeByCode(trailerType);
                    if (Objects.nonNull(transportationType)) {
                        if (transportationType.getValue() != null) {
                            if (transportationType.getValue().equals("三位平板")) {
                                xmlStr = xmlStr.replace("${PowerUnitTypeGid}", "平板三位板");
                            }
                            if (transportationType.getValue().equals("四位平板")) {
                                xmlStr = xmlStr.replace("${PowerUnitTypeGid}", "平板四位板");
                            }
                            if (transportationType.getValue().equals("六位平板")) {
                                xmlStr = xmlStr.replace("${PowerUnitTypeGid}", "六位车");
                            }
                            if (transportationType.getValue().equals("单车")) {
                                xmlStr = xmlStr.replace("${PowerUnitTypeGid}", "单车");
                            }
                            if (transportationType.getValue().equals("中置轴")) {
                                xmlStr = xmlStr.replace("${PowerUnitTypeGid}", "中置轴");
                            }
                            if (transportationType.getValue().equals("五位平板")) {
                                xmlStr = xmlStr.replace("${PowerUnitTypeGid}", "平板五位板");
                            }
                            if (transportationType.getValue().equals("七位平板")) {
                                xmlStr = xmlStr.replace("${PowerUnitTypeGid}", "七位车");
                            }
                        }
                    }
                }
            }
        }

        // 司机身份证号
        EntityWrapper<DriverCarrierBind> driverCarrierBindEntityWrapper = new EntityWrapper<>();
        driverCarrierBindEntityWrapper.eq("carrier_id", carrierInfo.getId());
        DriverCarrierBind driverCarrierBind = driverCarrierBindService.selectOne(driverCarrierBindEntityWrapper);
        if (Objects.nonNull(driverCarrierBind)) {
            driverId = driverCarrierBind.getDriverId();
            Driver driver = driverService.selectById(driverId);
            if (Objects.nonNull(driver)) {
                // 司机编码
                xmlStr = xmlStr.replace("${Attribute3}", prefix + driver.getId().toString());
                // 司机电话
                xmlStr = xmlStr.replace("${Attribute4}", driver.getMobile());
                //司机身份证
                EntityWrapper<DriverLicense> dlEW = new EntityWrapper<>();
                dlEW.eq("driver_id", driver.getId()).eq("license_type_id", 1);
                DriverLicense driverLicense = driverLicenseService.selectOne(dlEW);
                if (Objects.nonNull(driverLicense)) {
                    String sfLicense = driverLicense.getLicenseId();
                    if (sfLicense != null) {
                        xmlStr = xmlStr.replace("${Attribute1}", sfLicense);
                    }
                }
            }
        }

        String requestResult = HttpClientUtil.post(sendCarrierUrl, xmlStr);
        if (StringUtils.isEmpty(requestResult)) {
            throw new BaseException("OTM返回值为空");
        }
        try {
            requestResult = requestResult.replaceAll(" xmlns:ns2=\\\"http://xmlns.oracle.com/apps/gtm/transmission/v6.4\\\" xmlns=\\\"http://xmlns.oracle.com/apps/otm/transmission/v6.4\\\"", "");
            Document document1 = XmlUtil.parseByString(requestResult);
            String nodePath = "/TransmissionAck/EchoedTransmissionHeader/TransmissionHeader/ReferenceTransmissionNo";
            //得到根节点
            Element element = (Element) document1.selectSingleNode(nodePath);
            String requestId = element.getText();

            otmLisaCarrierService.insertOtmLisa(lspInfo.getId(), driverId, carrierId, trailerId, sendDriverUrl, requestId);
        } catch (Exception ex) {
            throw new BaseException(ex.getMessage());
        }
    }


    @Override
    public void sendDriverCheckin(DriverCheckin driverCheckin) throws BaseException {
        //判断报班对象是否为空
        if (Objects.isNull(driverCheckin)) {
            throw new BaseException("报班信息为空，不能上传到OTM ");
        }

        String filePath = "classpath:otmxml/truck_register.data.xml";
        Document document = getDocumentByFile(filePath);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String xmlStr = XmlUtil.xmlToString(document);

        // 报班编码
        xmlStr = xmlStr.replace("${TRUCK_REGISTER_XID}", driverCheckin.getId().toString());

        //司机
        Long driverId = driverCheckin.getDriverId();
        xmlStr = xmlStr.replace("${DRIVER}", driverId.toString());

        //分供方编码
        Long lspId = driverCheckin.getLspId();
        xmlStr = xmlStr.replace("${CARRIER}", lspId.toString());

        //报班时间 REGISTER_DATE
        Date gmtCheckin = driverCheckin.getGmtCheckin();
        String strGmtCheckin = formatter.format(gmtCheckin);
        xmlStr = xmlStr.replace("${REGISTER_DATE}", strGmtCheckin);

        //期望装车时间 期望装车时间
        Date gmtExpLoad = driverCheckin.getGmtExpLoad();
        String strGmtExpLoad = formatter.format(gmtExpLoad);
        xmlStr = xmlStr.replace("${P_ARRIVAL_DATE}", strGmtExpLoad);

        //报班起运城市
        String departRegion = driverCheckin.getDepartRegion();
        xmlStr = xmlStr.replace("${REGISTER_CITY}", departRegion);

        //预发运省份
        String destRegion = driverCheckin.getDestRegion();
        xmlStr = xmlStr.replace("${REGISTER_DEST_PRO}", destRegion);

        //可装载台数
        String amtExp = driverCheckin.getAmtExp();
        xmlStr = xmlStr.replace("${LOAD_QTY}", amtExp);

        //车牌号
        Long carrierId = driverCheckin.getCarrierId();
        CarrierInfo carrierInfo = carrierInfoService.selectById(carrierId);
        if (Objects.nonNull(carrierInfo)) {
            String carrierPlate = carrierInfo.getPlate();
            xmlStr = xmlStr.replace("${VEHICLE_NO}", carrierPlate);
        }

        //车挂号
        Long trailerId = driverCheckin.getTrailerId();
        TrailerInfo trailerInfo = trailerInfoService.selectById(trailerId);
        if (Objects.nonNull(trailerInfo)) {
            String trailPlate = trailerInfo.getPlate();
            xmlStr = xmlStr.replace("${VEHICLE_NO1}", trailPlate);
        }

        //运输方式 三位板
        String trailerType = trailerInfo.getTrailerType();
        if (Objects.nonNull(trailerType)) {
            TransportationTypeVO transportationType = mdmUtil.getTransportTypeByCode(trailerType);
            if (Objects.nonNull(transportationType)) {
                if (transportationType.getValue() != null) {
                    if (transportationType.getValue().equals("三位平板")) {
                        xmlStr = xmlStr.replace("${PowerUnitTypeGid}", "平板三位板");
                    }
                    if (transportationType.getValue().equals("四位平板")) {
                        xmlStr = xmlStr.replace("${PowerUnitTypeGid}", "平板四位板");
                    }
                    if (transportationType.getValue().equals("六位平板")) {
                        xmlStr = xmlStr.replace("${PowerUnitTypeGid}", "六位车");
                    }
                    if (transportationType.getValue().equals("单车")) {
                        xmlStr = xmlStr.replace("${PowerUnitTypeGid}", "单车");
                    }
                    if (transportationType.getValue().equals("中置轴")) {
                        xmlStr = xmlStr.replace("${PowerUnitTypeGid}", "中置轴");
                    }
                    if (transportationType.getValue().equals("五位平板")) {
                        xmlStr = xmlStr.replace("${PowerUnitTypeGid}", "平板五位板");
                    }
                    if (transportationType.getValue().equals("七位平板")) {
                        xmlStr = xmlStr.replace("${PowerUnitTypeGid}", "七位车");
                    }
                }
            }
        } else {
            xmlStr = xmlStr.replace("${PowerUnitTypeGid}", "");
        }


        //司机联系方式
        Driver driver = driverService.selectById(driverCheckin.getDriverId());
        if (Objects.nonNull(driver)) {
            String mobile = driver.getMobile();
            xmlStr = xmlStr.replace("${DRIVER_CONTACT_NO}", mobile);
        }

        String requestResult = HttpClientUtil.post(sendCheckInUrl, xmlStr);
        if (StringUtils.isEmpty(requestResult)) {
            throw new BaseException("OTM返回值为空");
        }

        System.out.print(requestResult);

//        try {
//            requestResult = requestResult.replaceAll(" xmlns:ns2=\\\"http://xmlns.oracle.com/apps/gtm/transmission/v6.4\\\" xmlns=\\\"http://xmlns.oracle.com/apps/otm/transmission/v6.4\\\"", "");
//            Document document1 = XmlUtil.parseByString(requestResult);
//            String nodePath = "/TransmissionAck/EchoedTransmissionHeader/TransmissionHeader/ReferenceTransmissionNo";
//            //得到根节点
//            Element element = (Element) document1.selectSingleNode(nodePath);
//            String requestId = element.getText();
//
//            otmLisaCarrierService.insertOtmLisa(lspId, driverId, carrierId, trailerId, sendCheckInUrl, requestId);
//        } catch (Exception ex) {
//            throw new BaseException(ex.getMessage());
//        }

    }


    /**
     * 文件转化为xml文档
     *
     * @param filePath
     * @return
     * @throws BaseException
     */
    private Document getDocumentByFile(String filePath) throws BaseException {
        Document document = null;
        try {
            File file = ResourceUtils.getFile(filePath);
            if (file.exists()) {
                document = XmlUtil.parseByFile(file);
            }
        } catch (Exception ex) {
            throw new BaseException(ex.getMessage());
        }
        return document;
    }

}
